//
//  UIView+Extension.swift
//  Test
//
//  Created by ZWJY on 2021/8/20.
//

import Foundation
import UIKit

// MARK: - 坐标处理
public extension UIView {
    
    var pg_x : CGFloat {
        get { frame.origin.x }
        set {
            var rect = frame
            rect.origin.x = newValue
            frame = rect
        }
    }

    var pg_maxX : CGFloat {
        get { frame.maxX }
    }

    var pg_y : CGFloat {
        get { frame.origin.y }
        set {
            var rect = frame
            rect.origin.y = newValue
            frame = rect
        }
    }

    var pg_maxY : CGFloat {
        get { frame.maxY }
    }

    var pg_width : CGFloat {
        get { frame.width }
        set {
            var rect = frame
            rect.size.width = newValue
            frame = rect
        }
    }

    var pg_height : CGFloat {
        get { frame.height }
        set {
            var rect = frame
            rect.size.height = newValue
            frame = rect
        }
    }

    var pg_size : CGSize {
        get { frame.size }
        set {
            var rect = frame
            rect.size = newValue
            frame = rect
        }
    }

    var pg_centerX : CGFloat {
        get { center.x }
        set {
            var point = center
            point.x = newValue
            center = point
        }
    }

    var pg_centerY : CGFloat {
        get { center.y }
        set {
            var point = center
            point.y = newValue
            center = point
        }
    }
}

// MARK: - 快速创建View
public extension UIView {

    ///快速创建View
    convenience init(backgroundColor: UIColor? = .white, alpha: CGFloat = 1) {
        self.init()
        self.backgroundColor = backgroundColor?.withAlphaComponent(alpha)
    }

    func pg_tag(_ tag: Int) -> Self {
        self.tag = tag
        return self
    }

    func pg_frame(_ frame: CGRect) -> Self {
        self.frame = frame
        return self
    }
    
    func pg_bounds(_ bounds: CGRect) -> Self {
        self.bounds = bounds
        return self
    }
    
    func pg_isHidden(_ hidden: Bool) -> Self {
        self.isHidden = hidden
        return self
    }
    
    func pg_backgroundColor(_ color: UIColor?, _ alpha: CGFloat = 1) -> Self {
        self.backgroundColor = color?.withAlphaComponent(alpha)
        return self
    }
    
    func pg_cornerRadius(_ cornerRadius: CGFloat) -> Self {
        self.layer.cornerRadius = cornerRadius
        self.layer.masksToBounds = true
        return self
    }
    
    func pg_addTapGesture(_ target: Any?, _ action: Selector?) -> Self{
        let tap = UITapGestureRecognizer.init(target: target, action: action)
        tap.numberOfTapsRequired = 1
        self.addGestureRecognizer(tap)
        return self
    }
    
    func pg_addDelayTapGesture(target: Any?, action: Selector?) -> Self {
        let tap = DelayTapGestureRecognizer.init(target: target, action: action)
        tap.numberOfTapsRequired = 1
        self.addGestureRecognizer(tap)
        return self
    }
    
    func pg_isUserInteractionEnabled(_ isUserInteractionEnabled: Bool) -> Self {
        self.isUserInteractionEnabled = isUserInteractionEnabled
        return self
    }
    
    func pg_border(_ width: CGFloat, _ color: UIColor?, _ alpha: CGFloat = 1) -> Self {
        self.layer.borderWidth = width
        self.layer.borderColor = color?.withAlphaComponent(alpha).cgColor
        return self
    }
}

// MARK: - 常见功能
public extension UIView {

    /// 绘制虚线
    /// - Parameters:
    ///   - strokeColor: 虚线颜色
    ///   - lineWidth: 虚线高度
    ///   - lineLength: 虚线长度
    ///   - lineSpacing: 虚线间距
    func drawDashLine(strokeColor: UIColor, lineWidth: CGFloat = 1, lineLength: CGFloat = 10, lineSpacing: Int = 5) {
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = self.bounds
        shapeLayer.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
//        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPhase = 0 //从哪个位置开始
        //每一段虚线长度 和 每两段虚线之间的间隔
        shapeLayer.lineDashPattern = [NSNumber(value: lineLength), NSNumber(value: lineSpacing)]
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: self.layer.bounds.width, y: 0))
        shapeLayer.path = path
        self.layer.addSublayer(shapeLayer)
    }
    
    /// 局部圆角（需要传入精确地bounds）
    func pg_corners(_ roundedRect: CGRect, _ byRoundingCorners: UIRectCorner, _ cornerRadii: CGSize ) {
        let path = UIBezierPath.init(roundedRect: roundedRect, byRoundingCorners: byRoundingCorners, cornerRadii: cornerRadii)
        let shapeLayer = CAShapeLayer.init()
        shapeLayer.frame = roundedRect
        shapeLayer.path = path.cgPath
        self.layer.mask = shapeLayer
    }
    
    func pg_addBorder(_ roundedRect: CGRect, _ byRoundingCorners: UIRectCorner, _ cornerRadii: CGSize, lineWidth: CGFloat, lineColor: UIColor?) {
        let path = UIBezierPath.init(roundedRect: roundedRect, byRoundingCorners: byRoundingCorners, cornerRadii: cornerRadii)
        // 局部圆角
        let shapeLayer = CAShapeLayer.init()
        shapeLayer.frame = roundedRect
        shapeLayer.path = path.cgPath
        self.layer.mask = shapeLayer
        
        // 边框线
        let borderLayer = CAShapeLayer.init()
        borderLayer.frame = roundedRect
        borderLayer.path = path.cgPath
        borderLayer.lineWidth = lineWidth
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = lineColor?.cgColor
        self.layer.addSublayer(borderLayer)
    }
    
    ///添加阴影(masksToBounds 会裁剪阴影，添加父类view 阴影实现效果)
    /// 使用局部阴影-添加父类处理
    func pg_shadow(_ shadowOpacity: Float, _ shadowColor: UIColor?, _ shadowRadius: CGFloat,  _ shadowOffset: CGSize = CGSize.zero) {
        // 透明度
        self.layer.shadowOpacity = shadowOpacity
        // 阴影颜色
        self.layer.shadowColor = shadowColor?.cgColor
        // 阴影偏移量
        self.layer.shadowOffset = shadowOffset
        // 阴影半径
        self.layer.shadowRadius = shadowRadius
    }

    /// 绘制渐变色
    /// startPoint(0, 0)->endPoint(0, 1.0); x相同，y控制方向，（从上至下）
    ///startPoint(0, 1.0)->endPoint(0, 0); x相同，y控制方向，（从下至上）
    ///startPoint(0, 0)->endPoint(1.0, 0); y相同，x控制方向，（从左至右）
    ///startPoint(1.0, 0)->endPoint(0, 0); y相同，x控制方向，（从右至左）
    ///startPoint(0, 0)->endPoint(1.0,1. 0); x，y控制方向，（从左上至右下）
    func pg_gradientColor(_ bounds: CGRect,_ startPoint: CGPoint, _ endPoint: CGPoint, _ gradientColors: [Any], _ gradientLocations: [NSNumber]? = nil) {
        let layer = CAGradientLayer.init()
        layer.startPoint = startPoint
        layer.endPoint = endPoint
        layer.locations = gradientLocations
        layer.colors = gradientColors
        layer.frame = bounds
        self.layer.insertSublayer(layer, at: 0)
    }
    
    /// 获取View 所在的控制器
    func pg_viewController() -> UIViewController? {
        var next = superview
        while (next != nil) {
            let nextResponder = next?.next
            if nextResponder is UINavigationController ||
                nextResponder is UIViewController {
                return nextResponder as? UIViewController
            }
            next = next?.superview
        }
        return nil
    }
    
    /// UIView转UIImage
    /// - Returns: UIImage
    func pg_convertedToImage(rect: CGRect = .zero) -> UIImage? {
        var size = bounds.size
        var origin = bounds.origin
        if !size.equalTo(rect.size) && !rect.isEmpty {
            size = rect.size
            origin = CGPoint(x: -rect.minX, y: -rect.minY)
        }
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        drawHierarchy(in: CGRect(origin: origin, size: bounds.size), afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

/**
 UIStackView使用技巧： 有四个最重要的属性, 只要设置好这四个属性就可以完美显示自动约束
 1， Axls: 子视图的布局方向, 可选值有:
 Vertical: 垂直
 Horizontal: 水平
 2，Alignment: 子视图在交叉轴的填充方式, 可选值有:
 Fill: 子视图填充 StackView.
 Leading: 所有子视图的左侧与 stackview 的左侧对齐
 Trailing: 所有子视图的右侧与 stackview 的右侧对齐
 Center: 所有子视图的中心线与 stackview 的中心线对齐
 Top: 所有子视图的顶部与 stackview 的顶部对齐
 Bottom: 所有子视图的顶部与 stackview 的底部对齐
 First Baseline: 按照第一个子视图中文字的第一行对齐.
 Last Baseline: 按照最后一个子视图中文字的最后一行对齐.
 3，Distributlon: 子视图的分布比例 (大小), 可选值有:
 Fill: 默认分布方式.

 不能再设置控件的宽高约束, 否则会约束冲突.

 Fill Equally: 每个子视图的高度或宽度保持一致.

 使每个子视图的宽度或高度相等

 不能再设置控件的宽高约束, 否则会约束冲突.

 Fill Proportionally: StackView 自己计算出它认为合适的分布方式.

 系统将完全不考虑空间自身的宽高, 完全依据控件的内容自行布置出系统认为合适的布局

 不能再设置控件的宽高约束, 否则会约束冲突

 Equal Spacing: 每个子视图保持同等间隔的分布方式.

 横向布局前提下, 如果设置的 spacing 值加上横向三个控件的总宽度小于 stackview 的宽度时, 三个控件的间距相等, 即最左最右各一个, 中间居中一个. 如果总宽度大于 stackview 的宽度, 则控件间的间距为 spacing 值. 如果只有两个控件横向布局时, 且 spacing 与控件宽度之和小于 stackview 的宽度, 则两个空间一左一右靠边对齐

 可为控件通过自动布局指定宽高, 如果不设置宽度的话使用此选项会优先拉伸子控件的宽度, 而不是使用等距设置

 Equal Centering: 每个子视图中心线之间保持一致的分布方式.

 可为控件通过自动布局指定宽高, 如果不设置宽度的话使用此选项会优先拉伸子控件的宽度, 而不是使用等距设置

 4，Spacing: 子试视图间的间距
 UIStackView 中只有 Distribution 为 Equal Spacing 或 Equal Centering 时才可设置子控件的宽高约束, 而且不能通过 frame 指定宽高, 必须使用自动布局.

 */
